package cn.monkey.family.server.domain.uc.role;

import cn.monkey.family.data.Result;
import cn.monkey.family.data.Results;
import cn.monkey.family.data.context.RequestContext;
import cn.monkey.family.data.crud.AbstractCrudService;
import cn.monkey.family.data.uc.role.*;
import com.google.common.base.Strings;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class RoleService extends AbstractCrudService<String, RoleQueryRequest, Role, RoleDto, RoleVo, RoleMapper, RoleRepository> implements IRoleService {

    protected final AfterRoleSavedEventListener afterRoleSavedEventListener;

    protected final BeforeRoleDeletedEventListener beforeRoleDeletedEventListener;

    public RoleService(RoleRepository repository,
                       RoleMapper mapper,
                       AfterRoleSavedEventListener afterRoleSavedEventListener,
                       BeforeRoleDeletedEventListener beforeRoleDeletedEventListener) {
        super(repository, mapper);
        this.afterRoleSavedEventListener = afterRoleSavedEventListener;
        this.beforeRoleDeletedEventListener = beforeRoleDeletedEventListener;
    }


    @Override
    public Result<RoleVo> create(RequestContext requestContext, RoleDto roleDto) {
        Role role = this.repository.save(this.mapper.toEntity(roleDto));
        String orgId = requestContext.getOrgId();
        if (Strings.isNullOrEmpty(orgId)) {
            return Results.ok(this.mapper.toVo(role));
        }
        this.afterRoleSavedEventListener.onEvent(requestContext, role);
        return Results.ok(this.mapper.toVo(role));
    }

    @Override
    public Result<Void> delete(RequestContext requestContext, String s) {
        Optional<Role> roleOptional = this.repository.findById(s);
        if (roleOptional.isEmpty()) {
            return Results.notFound();
        }
        Result<Void> result = this.beforeRoleDeletedEventListener.beforeRoleDeleted(requestContext, roleOptional.get());
        if (!Results.isOk(result)) {
            return result;
        }
        this.repository.deleteById(s);
        return Results.ok();
    }
}
